;; -*- Lisp -*-

(defpackage #:cl-gdbm-system
  (:use #:common-lisp #:asdf))

(in-package #:cl-gdbm-system)

(eval-when (:compile-toplevel :load-toplevel :execute)
  (asdf:oos 'asdf:load-op :uffi))

(defvar *lib-loaded-p* nil)

(defmethod perform ((o load-op) (c c-source-file))
  (uffi:load-foreign-library (make-pathname :name "cl-gdbm-stub"
					    :type (uffi:default-foreign-library-type)
					    :directory (pathname-directory
							#.*load-truename*))
			     :module "cl-gdbm-stub.so"
			     :supporting-libraries '("c"))
  (setf *lib-loaded-p* t))

(defmethod operation-done-p ((o load-op) (c c-source-file))
  *lib-loaded-p*)

(defmethod perform ((o compile-op) (c c-source-file))
  (unless (operation-done-p o c)
    #-(or win32 mswindows)
    (unless (zerop (run-shell-command
		    #-freebsd "cd ~A; make"
		    #+freebsd "cd ~A; gmake"
		    (namestring (make-pathname :name nil
					       :type nil
					       :directory (pathname-directory
							   #.*load-truename*)))))
      (error 'operation-error :component c :operation o))))

(defmethod operation-done-p ((o compile-op) (c c-source-file))
  (or (and (probe-file #p"/usr/lib/cl-gdbm/cl-gdbm-stub.so") t)
      (let ((lib (make-pathname :defaults (component-pathname c)
				:type (uffi:default-foreign-library-type))))
	(and (probe-file lib)
	     (> (file-write-date lib) (file-write-date (component-pathname c)))))))


(defsystem cl-gdbm
    :author "Peter Scott"
    :components ((:file "package")
		 (:c-source-file "cl-gdbm-stub")
		 (:file "utilities" :depends-on ("package"))
		 (:file "gdbm-ffi" :depends-on ("package" "cl-gdbm-stub"))
		 (:file "high-level" :depends-on ("package"
						  "gdbm-ffi"
						  "utilities")))
    :depends-on (uffi))